﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;

namespace PageEditing
{
	public class CssPageEditBizRules : Syrinx.BaseBizRules
	{
		protected Regex s_skinRegex = new Regex(@"<swf:DivLayers.*?SkinID=""([^""]+)""/>", RegexOptions.Singleline);

		public IBizObjList getSkinIdsForSalFromCurrentTheme(IApplication app, IRuleContext context)
		{
			string curTheme = (string)ActiveCompany.get("settings.themeName");
			IResults rc = context.RuleGroup.execute(context, "getSkinIdsForSalFromTheme", curTheme);
			return rc.CallResults as IBizObjList;
		}

		public IBizObjList getSkinIdsForSalFromTheme(IApplication app, IRuleContext context, string themeName)
		{
			IBizObjList skins = app.bizObjMgr.createList("SalSkin");
			string root = app.resMgr.resolve("$ConfigParam1$");
			string skinFile = Cmn.pathCombine(root, "App_Themes", themeName, "ArticleBoxSkins.skin");
			if (skinFile.StartsWith("file:\\\\", StringComparison.CurrentCultureIgnoreCase))
				skinFile = skinFile.Substring(7);

			IBizObj unspec = skins.insertNew();
			unspec.put("name", "");
			if (File.Exists(skinFile))
			{
				string skinContents = File.ReadAllText(skinFile);
				MatchCollection mc = s_skinRegex.Matches(skinContents);
				foreach (Match m in mc)
				{
					IBizObj skin = skins.insertNew();
					skin.put("name", m.Groups[1].Value);
				}
			}

			return skins;
		}

		public IBizObjList getImageSizesForSal(IApplication app, IRuleContext context)
		{
			IBizObjList scalings = null;
			IResults rc = app.ruleMgr.execute("getImageCacheDetails", ActiveCompany.get("settings.defaultMediaCatalogName"));
			IBizObj cacheInfo = rc.CallResults as IBizObj;
			if (cacheInfo != null)
				scalings = cacheInfo.get("scalings.[0].adjustments") as IBizObjList;
			if (scalings != null)
			{
				IBizObj unspec = scalings.insertNew();//app.bizObjMgr.create(scalings.objectType.Name);
				unspec.put("name", "");
			}
			return scalings;
		}
	}
}
